using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;


namespace SoSlam.Common.ClientLogic
{
    /// <summary>
    /// This is a game component that implements IUpdateable.
    /// </summary>
    public class Cloud : DrawableGameComponent
    {
        private World _world;
        private TrackingCamera _camera;

        private Texture2D _cloudSprite;
        private SpriteBatch _spriteBatch;

        private const float _timeAdjustmentFactor = 10f;

        private float _scaleFactor;
        private Vector2 _speed;
        private Vector2 _position;
        private Vector2 _trackedPosition;

        public Vector2 Position { get { return _trackedPosition; } }
        public int Width { get { return (int)(_cloudSprite.Width * _scaleFactor); } }

        public Cloud(Game game, World world, TrackingCamera camera)
            : base(game)
        {
            _world = world;
            _camera = camera;
        }

        public override void Initialize()
        {
            _spriteBatch = new SpriteBatch(Game.GraphicsDevice);

            _scaleFactor = 1.0f + (float)World.Random.NextDouble() % 2;
            _speed = new Vector2(3, 0);

            base.Initialize();
        }

        protected override void LoadContent()
        {
            var i = 1 + (int)(World.Random.NextDouble() * 100) % 4;
            _cloudSprite = Game.Content.Load<Texture2D>("Sprites/cloud0" + i);

            // Initial position : hidden on the right side of the screen
            _position = new Vector2();
            _position.X = _world.GraphicsDevice.Viewport.Width + _camera.Position.X;
            _position.Y = _world.Player.Position.Y - _cloudSprite.Height * _scaleFactor - (float)(World.Random.NextDouble() * 2 * _camera.Fov.Height);
            if (_position.Y > -400)
                _position.Y -= 400;

            _trackedPosition = _position - _camera.Position;

            base.LoadContent();
        }

        public override void Update(GameTime gameTime)
        {
            _position.X = _position.X - ((float)gameTime.ElapsedGameTime.TotalSeconds * _timeAdjustmentFactor) * _speed.X;
            _trackedPosition = _position - _camera.Position;

            base.Update(gameTime);
        }

        public override void Draw(GameTime gameTime)
        {
            _spriteBatch.Begin();

            _spriteBatch.Draw(_cloudSprite, _trackedPosition, null, Color.White, 0f, new Vector2(), _scaleFactor, SpriteEffects.None, 1f);

            _spriteBatch.End();

            base.Draw(gameTime);
        }
    }
}
